# -*- coding: utf-8 -*-

from odoo import api,models,fields

import pytz

from odoo.addons.base.models.ir_sequence import _alter_sequence


class IRSequence(models.Model):
    _inherit = "ir.sequence"

    loop_type = fields.Selection(selection=[('year', u'年'), ('month', u'月'), ('day', u'日')], string=u'循环类型')
    loop_time = fields.Datetime(string=u'循环日期', default=fields.Datetime.now)

    def alert_sequence(self, number_increment=None, number_next=None):
        numbervals = {}
        if not number_increment:
            number_increment = self.number_increment
        else:
            numbervals['number_increment'] = number_increment
        if not number_next:
            number_next = self.number_next
        else:
            numbervals['number_next'] = number_next
        if numbervals and len(numbervals) > 0:
            self.sudo().write(numbervals)
        _alter_sequence(self.env.cr, "ir_sequence_%03d" % self.id, number_increment=number_increment, number_next=number_next)


    def convert2timezonetime(self, origintime, tzname='Asia/Shanghai'):
        temptime = pytz.timezone('UTC').localize(origintime, is_dst=False)
        return temptime.astimezone(pytz.timezone(tzname))


    @api.model
    def next_by_code(self, sequence_code,sequence_date=None):
        temp_sequence = self.env['ir.sequence'].search([('code', '=', sequence_code)], limit=1)
        if not temp_sequence or not temp_sequence.loop_type:
            return super(IRSequence, self).next_by_code(sequence_code)
        tz_name = self.env.user.tz or self.env.context.get('tz') or 'Asia/Shanghai'
        temptime = fields.Datetime.from_string(temp_sequence.loop_time)
        loopdate = self.convert2timezonetime(temptime, tzname=tz_name).strftime('%Y-%m-%d')
        currenttime = fields.Datetime.from_string(fields.Datetime.now())
        currentdate = self.convert2timezonetime(currenttime, tzname=tz_name).strftime('%Y-%m-%d')
        temp_type, temp_flag = temp_sequence.loop_type, False
        if (temp_type == 'year') and (currentdate[0:4] != loopdate[0:4]):
            temp_flag = True
        elif (temp_type == 'month') and (currentdate[0:7] != loopdate[0:7]):
            temp_flag = True
        elif (temp_type == 'day') and (currentdate != loopdate):
            temp_flag = True
        if temp_flag:
            temp_sequence.sudo().alert_sequence(number_increment=1, number_next=1)
            temp_sequence.sudo().write({'loop_time': fields.Datetime.now()})
        return super(IRSequence, self).next_by_code(sequence_code, sequence_date=sequence_date)
